/**
 * @file 查询优惠
 * @author wangxiaokun
 * @date 2018/12/14 16:38:57
 */

layui.define(['table', 'form', '$http', 'layer'], function (exports) {
    var $ = layui.$;
    var table = layui.table;
    var form = layui.form;
    var $http = layui.$http;
    var layer = layui.layer;

    var options;
    var promotionTable;
    var discountTable;
    var thirdDiscountTable;
    var incrementTable;
    var showDiscountDTO;

    // 获取省份、城市、区域
    var CITY_URL = "/area/channel/city/list.action";
    // 获取产品列表
    var PRODUCT_URL = "/serv/product/list.action";
    // 检查是否有优惠
    var CHECK_DISCOUNT_URL = "/common/check/discount.action";

    /**
     * 渲染增值优惠表格
     * @returns {object}
     */
    function renderIncrementTable() {
        incrementTable = table.render({
            elem: "#zmn-increment-table",
            width: 1096,
            data: [],
            cols: [[
                { field: 'incrementProductName', title: '关联增值产品名称', width:122, align: 'center' },
                { field: 'incrementProductPrice', title: '关联增值产品售价', width:122, align: 'center' },
                { field: 'originalPrice', title: '关联增值产品原价', width:122, align: 'center'},
                { field: 'discountType', title: '优惠券类型', width:80, align: 'center'},
                { field: 'quota', title: '额度', width:70, align: 'center'},
                { field: 'useCondition', title: '使用条件', width:100, align: 'center'},
                { field: 'periodValidity', title: '有效期', width:300, align: 'center'},
                { field: 'desc', title: '说明', width:179, align: 'center'}
            ]],
            done: function () {},
            even: true,
        });
    }

    /**
     * 渲染促销优惠表格
     * @returns {object}
     */
    function renderPromotionTable() {
        promotionTable = table.render({
            elem: "#zmn-promotion-table",
            width: 1096,
            data: [],
            cols: [[
                { field: 'discountTypeName', title: '优惠方式', width:70, align: 'center', templet: function (d) {
                        return '<span style="background-color:#FF6600">' + d.discountTypeName + '</span>';
                    } },
                { field: 'discountInfo', title: '减免力度', width:170, align: 'center' },
                { field: 'discountTime', title: '优惠时间', width:300, align: 'center'},
                { field: 'desc', title: '说明', width:551, align: 'center'}
            ]],
            done: function () {},
            even: true,
        });
    }

    /**
     * 渲染第三方活动优惠表格
     * @returns {object}
     */
    function renderThirdDisountTable() {
        thirdDiscountTable = table.render({
            elem: "#zmn-third-discount",
            width: 1096,
            data: [],
            cols: [[
                { field: 'desc', title: '活动说明', width:1094, align: 'center' }
            ]],
            done: function () {},
            even: true,
        });
    }

    /**
     * 渲染用户优惠表格
     * @returns {object}
     */
    function renderDiscountTable() {
        discountTable = table.render({
            elem: "#zmn-discount-table",
            width: 1096,
            data: [],
            cols: [[
                { field: 'discountTypeName', title: '优惠券类型', width:100, align: 'center' },
                { field: 'quota', title: '额度', width:100, align: 'center'},
                { field: 'useCondition', title: '使用条件', width:150, align: 'center'},
                { field: 'periodValidity', title: '有效期', width:290, align: 'center'},
                { field: 'desc', title: '说明', width:449, align: 'center'}
            ]],
            done: function () {},
            even: true
        });
    }

    /**
     * 渲染城市选择下拉框
     * @param provinceId 省份ID
     */
    function initCitySelect(provinceId) {
        fetchCityData(provinceId).done(function (data) {
            renderCitySelect(data);
        });
    }

    /**
     * 根据省份 id 远程获取城市数据
     * @param provinceId 城市 id
     */
    function fetchCityData(provinceId) {
        return fetchAreaDataByParentId(CITY_URL, {
            provinceId: provinceId,
            channelId: showDiscountDTO.channelId,
            showType: 2,
        });
    }

    /**
     * 根据父级 id 远程获取下级区域数据
     * @param {string} url 地址
     * @param {object} params 参数
     */
    function fetchAreaDataByParentId(url, params) {
        return $http.get(url, params).then(
            function (data) {
                return data;
            },
            function () {
                layer.msg("获取数据失败");
                return $.Deferred().resolve([]);
            }
        );
    }

    /**
     * 渲染城市选择下拉框
     * @param {array} data 城市数据
     */
    function renderCitySelect(data) {
        var htmlStr = '<option value="">全部</option>';

        $.each(data, function (index, item) {
            htmlStr += '<option value="' + item.value + '">' + item.text + '</option>';
        });

        $("#cityId").html(htmlStr);
        form.render("select");
    }

    /**
     * 初始化城市下拉框
     */
    var initProductSelect = (function () {
        /**
         * 根据配件一级分类获取二级分类
         * @param params 查询参数
         * @returns {*}
         * @private
         */
        function _fetchProductByParent (params) {
            return $http.$get(PRODUCT_URL, params);
        }

        /**
         * 渲染配件小类下拉框
         * @param {object} data 区域数据
         * @private
         */
        function _renderProductSelect (data) {
            var htmlStr = '<option value="">全部</option>';
            data.forEach(function (item) {
                htmlStr += '<option value="' + item.value + '">' + item.text + '</option>';
            });

            $('#showProductId').html(htmlStr);
            form.render();
        }

        return function (servCategId) {
            if (!servCategId) {
                _renderProductSelect([]);
            }

            _fetchProductByParent({
                servCategId: servCategId,
                plat: showDiscountDTO.plat,
                channelId: showDiscountDTO.channelId,
                cityId: $("#cityId").val(),
                bizType: showDiscountDTO.bizType,
                showType: 2
            }).then((data) => {
                _renderProductSelect(data);
            }, () => {
                _renderProductSelect([]);
            });
        }
    })();

    /**
     * 初始化所有表格
     * @param options
     */
    function initAllTable(options) {

        if (options == undefined) {
            return;
        }
        if (options.promotionDiscountList != undefined && options.promotionDiscountList.length != 0){
            $(".non-promotion").addClass("layui-hide");
            renderPromotionTable();
            promotionTable.reload({
                data: options.promotionDiscountList,
            })
        } else {
            $("div[lay-id='zmn-promotion-table']").addClass("layui-hide");
            $(".non-promotion").removeClass("layui-hide");
        }
        if (options.userDiscountList  != undefined && options.userDiscountList.length != 0){
            $(".non-discount").addClass("layui-hide");
            renderDiscountTable();
            discountTable.reload({
                data: options.userDiscountList,
            })
        } else {
            $("div[lay-id='zmn-discount-table']").addClass("layui-hide");
            $(".non-discount").removeClass("layui-hide");
        }
        if (options.thirdDiscountList  != undefined && options.thirdDiscountList.length != 0){
            $(".non-third").addClass("layui-hide");
            renderThirdDisountTable();
            thirdDiscountTable.reload({
                data: options.thirdDiscountList,
            })
        } else {
            $("div[lay-id='zmn-third-discount']").addClass("layui-hide");
            $(".non-third").removeClass("layui-hide");
        }
        if (options.incrementDiscountList  != undefined && options.incrementDiscountList.length != 0){
            $(".non-increment").addClass("layui-hide");
            renderIncrementTable();
            incrementTable.reload({
                data: options.incrementDiscountList,
            })
        } else {
            $("div[lay-id='zmn-increment-table']").addClass("layui-hide");
            $(".non-increment").removeClass("layui-hide");
        }
    }

    function initSelectAndSubmit(provinceId, cityId, servCategId, showProductId) {
        $("#provinceId").val(provinceId);
        // 渲染城市下拉框
        initCitySelect(provinceId);
        //form.val('zmn-work-form', {cityId: cityId});
        $("#cityId").val(cityId);
        $("#servCategoryId").val(servCategId);
        // 初始化产品下拉框
        initProductSelect(servCategId);
        $("#showProductId").val(showProductId);
        form.render("select");
        $("#submit-search").trigger('click');
    }

    /**
     * 初始化页面
     */
    function initPage () {
        options = parent.window.showDiscountOptions;
        showDiscountDTO = options.showDiscountDTO;
        initAllTable(options);
        if (showDiscountDTO.cityId && showDiscountDTO.showProductId) {
            initSelectAndSubmit(showDiscountDTO.provinceId, showDiscountDTO.cityId, showDiscountDTO.servCategId,
                showDiscountDTO.showProductId);
        }
    }

    function initEvent () {

        // 请求全部为同步
        $.ajaxSetup({
            async : false
        });

        form.render();

        // 省份选择下拉框的点击事件处理器
        form.on("select(province)", function (data) {
            // 渲染城市下拉框
            initCitySelect(data.value);
        });

        // 服务分类事件
        form.on("select(servCategoryId)", function (data) {
            // 初始化产品下拉框
            initProductSelect(data.value);
        });

        // 查询优惠事件
        form.on("submit(submit-search)", function (data) {
            let productId = $("#showProductId").val();
            let cityId = $("#cityId").val();
            // 渠道id
            if (!productId) {
                return false;
            }

            // 城市id
            if (!cityId) {
                return false;
            }

            $http.$get(CHECK_DISCOUNT_URL, {
                    plat: showDiscountDTO.plat,
                    channelId: showDiscountDTO.channelId,
                    cityId: cityId,
                    productId: productId,
                    bizType: showDiscountDTO.bizType,
                    servItemType: showDiscountDTO.servItemType,
                }).then(
                    function (data) {
                        initAllTable(data);
                    },
                    function (msg) {
                        layer.msg(msg);
                    }
                );

        });

        // 监听重置按钮点击
        form.on('submit(submit-reset)', function (obj) {
            setTimeout(function () {
                $('select').val('');
                form.render('select');
            }, 100);

            return false;
        });
    }

    function init () {
        initEvent();

        initPage();
    }

    init();

    exports("oms_work_modify_selectDiscount");
});
